import { FieldInfo, MysqlError, QueryOptions } from "mysql";

export const mysqlQuery: (
  sql: string | QueryOptions,
  query: any
) => Promise<{
  err: MysqlError | null;
  results?: any;
  fields?: FieldInfo[];
}> = (sql, query) =>
  new Promise((resolve, reject) => {
    global.mysqldb.query(sql, query, (err, results, fields) => {
      if (err) {
        reject(err);
      } else {
        resolve({
          err,
          results,
          fields,
        });
      }
    });
  });

export const mysqlpoolQuery = (
  sql: string | QueryOptions,
  query: any
): Promise<{
  err: MysqlError | null;
  results?: any;
  fields?: FieldInfo[];
}> => {
  return new Promise((resolve, reject) => {
    global.mysqlpool.getConnection((err, connect) => {
      if (err) {
        reject(err);
      } else {
        connect.query(sql, query, (err, results, fields) => {
          if (err) {
            reject(err);
          } else {
            resolve({ err, results, fields });
          }
        });
      }
    });
  });
};
